<?php

namespace app\common\controller;

use app\common\library\AdminAuth;
use think\Config;
use think\Controller;
use think\Cookie;
use think\exception\HttpResponseException;
use think\Hook;
use think\Lang;
use think\Loader;
use think\Request;
use think\Db;
use think\Response;
use fast\Random;
use fast\Http;
/**
 * 前台控制器基类
 */
class MobileFrontend extends Controller
{

    /**
     * 布局模板
     * @var string
     */
    protected $layout = '';

    /**
     * 无需登录的方法,同时也就不需要鉴权了
     * @var array
     */
    protected $noNeedLogin = [];

    /**
     * 无需鉴权的方法,但需要登录
     * @var array
     */
    protected $noNeedRight = [];

    /**
     * 权限Auth
     * @var Auth
     */
    protected $auth = null;

    protected $responseType = 'json';


    public function _initialize()
    {
        //移除HTML标签
	
        $this->request->filter('trim,strip_tags,htmlspecialchars');
        $modulename = $this->request->module();
        $controllername = Loader::parseName($this->request->controller());
        $actionname = strtolower($this->request->action());

        // 如果有使用模板布局
        if ($this->layout) {
			
            $this->view->engine->layout('layout/' . $this->layout);
        }
        $this->auth = AdminAuth::instance();

		
        // token
        //$token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));
		$token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));
      
		$path = str_replace('.', '/', $controllername) . '/' . $actionname;
        // 设置当前请求的URI
      
	   $this->auth->setRequestUri($path);
        // 检测是否需要验证登录
	 
        if (!$this->auth->match($this->noNeedLogin)) {
            //初始化
           $d=$this->auth->init($token);
			 
            //检测是否登录
            if (!$this->auth->isLogin()) {
                $request = Request::instance();
                $redirect_url = $request->domain() . $request->baseUrl();
                // 实例接口
                $wechat = new \WeChat\Oauth(get_wx_config());
                if(!$request->get('code')){
                    $state = null;
                    $scope = 'snsapi_userinfo';
                    $result = $wechat->getOauthRedirect($redirect_url, $state, $scope);
                    header("Location:" . $result);
                    exit;
                }else{
                    $wxinfo = $wechat->getOauthAccessToken();
                    $admin = Db::name('user')->where("open_id",$wxinfo['openid'])->find();
                    if ($admin)
                    { 
                        //如果已经有账号则直接登录
                        $ret = $this->auth->direct($admin['id']);
                        header("Location:" . $redirect_url);
                        exit;
                    }else{
                        //获取用户信息
						$get_user='https://api.weixin.qq.com/sns/userinfo?access_token=' . $wxinfo['access_token']. '&openid=' . $wxinfo['openid'];
						$user_info=Http::sendRequest($get_user);
						$duser=json_decode($user_info['msg'],true);
						$duser['token'] = Random::uuid();
						
						$user=array('open_id'=>$duser['openid'],'token'=>$duser['token'],'nickname'=>$duser['nickname'],'avatar'=>$duser['headimgurl'],'logintime'=>time(),'loginip'=>$this->request->ip(),'createtime'=>time(),'updatetime'=>time(),'status'=>'normal');
						$bind_shop=db('bind_shop')->where('openid',$duser['openid'])->find();
						 
						if(!empty($bind_shop)){
							$user['shop_id']=$bind_shop['shopid'];
						}else{
							$user['shop_id']=1;
						}
						$udd=$this->thirdlogin($user);
						if($udd){
							$ret = $this->auth->direct($udd);
							header("Location:" . $redirect_url);
							exit; 
						}else{
							$this->error('登录失败');
						}
						 
                       // header("Location:".$request->domain().'/mobile/admin/bind?open_id='.$wxinfo['openid']);
                        exit;
                    }
                }
            }
            // 判断是否需要验证权限
            if (!$this->auth->match($this->noNeedRight)) {
                // 判断控制器和方法判断是否有对应权限
                if (!$this->auth->check($path)) {
                    $this->error(__('You have no permission'));
                }
            }
        } else {
			
            // 如果有传递token才验证是否登录状态
            if ($token) {
                $this->auth->init($token);
            }
        }
		
			 
		$this->view->assign('host', $this->request->domain());
        $this->view->assign('user', $this->auth->getUser());

        // 语言检测
        $lang = strip_tags($this->request->langset());

        $site = Config::get("site");

        $upload = \app\common\model\Config::upload();

        // 上传信息配置后
        Hook::listen("upload_config_init", $upload);

        // 配置信息
        $config = [
            'site'           => array_intersect_key($site, array_flip(['name', 'cdnurl', 'version', 'timezone', 'languages'])),
            'upload'         => $upload,
            'modulename'     => $modulename,
            'controllername' => $controllername,
            'actionname'     => $actionname,
            'jsname'         => 'frontend/' . str_replace('.', '/', $controllername),
            'moduleurl'      => rtrim(url("/{$modulename}", '', false), '/'),
            'language'       => $lang
        ];
        $config = array_merge($config, Config::get("view_replace_str"));

        Config::set('upload', array_merge(Config::get('upload'), $upload));

        // 配置信息后
        Hook::listen("config_init", $config);
        // 加载当前控制器语言包
        $this->loadlang($controllername);
        $this->assign('site', $site);
        $this->assign('config', $config);
    }
	protected function thirdlogin($user){
		if(empty($user['open_id'])||empty($user['token'])){
			 $this->error('信息有误','',0);
		}
		Db::startTrans();
		try {
			$uid=db('user')->insertGetId($user);
			Db::commit();
		}catch (\Exception $e) {
			Db::rollback();
			//$this->error($e->getMessage(),'',0);
			return false;
        }
		return $uid;
	}
    /**
     * 加载语言文件
     * @param string $name
     */
    protected function loadlang($name)
    {
        Lang::load(APP_PATH . $this->request->module() . '/lang/' . $this->request->langset() . '/' . str_replace('.', '/', $name) . '.php');
    }

    /**
     * 渲染配置信息
     * @param mixed $name  键名或数组
     * @param mixed $value 值
     */
    protected function assignconfig($name, $value = '')
    {
        $this->view->config = array_merge($this->view->config ? $this->view->config : [], is_array($name) ? $name : [$name => $value]);
    }

    /**
     * 返回封装后的 API 数据到客户端
     * @access protected
     * @param mixed  $msg    提示信息
     * @param mixed  $data   要返回的数据
     * @param int    $code   错误码，默认为0
     * @param string $type   输出类型，支持json/xml/jsonp
     * @param array  $header 发送的 Header 信息
     * @return void
     * @throws HttpResponseException
     */
    protected function result($msg, $data = null, $code = 0, $type = null, array $header = [])
    {
        $result = [
            'code' => $code,
            'msg'  => $msg,
            'time' => Request::instance()->server('REQUEST_TIME'),
            'data' => $data,
        ];
        // 如果未设置类型则自动判断
        $type = $type ? $type : ($this->request->param(config('var_jsonp_handler')) ? 'jsonp' : $this->responseType);

        if (isset($header['statuscode'])) {
            $code = $header['statuscode'];
            unset($header['statuscode']);
        } else {
            //未设置状态码,根据code值判断
            $code = $code >= 1000 || $code < 200 ? 200 : $code;
        }
        $response = Response::create($result, $type, $code)->header($header);
        throw new HttpResponseException($response);
    }

    /**
     * 返回数据
     */
    public function callBack($code = null,$msg = null,$data = null,$type = 'json'){

        $this->result($msg,$data,$code,$type);
    }


    protected function success($msg = '', $data = null, $code = 1, $type = null, array $header = [])
    {
        $this->result($msg, $data, $code, $type, $header);
    }

    /**
     * 操作失败返回的数据
     * @param string $msg    提示信息
     * @param mixed  $data   要返回的数据
     * @param int    $code   错误码，默认为0
     * @param string $type   输出类型
     * @param array  $header 发送的 Header 信息
     */
    protected function errord($msg = '', $data = null, $code = 0, $type = null, array $header = [])
    {
        $this->result($msg, $data, $code, $type, $header);
    }
	public function alert_error($msg){
		echo $msg; die;
	}
}
